package com.example.mark.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mark.common.Result;
import com.example.mark.entity.Topic;
import com.example.mark.mapper.TopicMapper;
import com.example.mark.mapper.RecoverTopicMapper;
import com.example.mark.service.TopicService;
import com.example.mark.vo.TopicDetailVO;
import com.example.mark.vo.RecoverVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic> implements TopicService {
    
    @Autowired
    private RecoverTopicMapper recoverTopicMapper;

    @Override
    public Result getTopicList() {
        QueryWrapper<Topic> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("createtime");
        List<Topic> topicList = this.list(queryWrapper);
        return Result.success(topicList);
    }

    @Override
    public Result getHotTopicList() {
        QueryWrapper<Topic> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("reply_number");  // 按回复数降序排序
        List<Topic> topicList = this.list(queryWrapper);
        return Result.success(topicList);
    }

    @Override
    public Result publishTopic(Map<String, Object> requestParams) {
        try {
            Topic topic = new Topic();
            topic.setTopicUserId((int) requestParams.get("topicUserId"));
            topic.setTitle((String) requestParams.get("title"));
            topic.setTopicContext((String) requestParams.get("topicContent"));
            topic.setCreatetime(LocalDateTime.now());
            topic.setVerify(0);  // 默认未审核
            topic.setReplyNumber(0);  // 初始回复数为0
            topic.setSchool((String) requestParams.get("school"));
            topic.setTag((String) requestParams.get("tag"));
            topic.setTopicPhoto((String) requestParams.get("topicPhoto"));
            
            boolean success = this.save(topic);
            if (success) {
                return Result.success("话题发布成功，请耐心等待审核");
            } else {
                return Result.error("话题发布失败，请稍后再试");
            }
        } catch (Exception e) {
            return Result.error("发布话题时发生错误：" + e.getMessage());
        }
    }

    @Override
    public Result updateTopic(Map<String, Object> requestParams) {
        try {
            int topicId = (int) requestParams.get("topicId");
            
            Topic topic = baseMapper.selectByTopicId(topicId);
            if (topic == null) {
                return Result.error("话题不存在");
            }
            
            if (requestParams.containsKey("title")) {
                topic.setTitle((String) requestParams.get("title"));
            }
            if (requestParams.containsKey("topicContent")) {
                topic.setTopicContext((String) requestParams.get("topicContent"));
            }
            if (requestParams.containsKey("verify")) {
                topic.setVerify((int) requestParams.get("verify"));
            }
            if (requestParams.containsKey("school")) {
                topic.setSchool((String) requestParams.get("school"));
            }
            if (requestParams.containsKey("tag")) {
                topic.setTag((String) requestParams.get("tag"));
            }
            if (requestParams.containsKey("topicPhoto")) {
                topic.setTopicPhoto((String) requestParams.get("topicPhoto"));
            }
            
            int rows = baseMapper.updateByTopicId(topic);
            if (rows > 0) {
                return Result.success("话题更新成功");
            } else {
                return Result.error("话题更新失败，请稍后再试");
            }
        } catch (Exception e) {
            return Result.error("更新话题时发生错误：" + e.getMessage());
        }
    }

    @Override
    public Result deleteTopic(int topicId) {
        try {
            // 先查询话题是否存在
            Topic topic = baseMapper.selectByTopicId(topicId);
            if (topic == null) {
                return Result.error("话题不存在");
            }
            
            int rows = baseMapper.deleteByTopicId(topicId);
            if (rows > 0) {
                return Result.success("话题删除成功");
            } else {
                return Result.error("话题删除失败，请稍后再试");
            }
        } catch (Exception e) {
            return Result.error("删除话题时发生错误：" + e.getMessage());
        }
    }

    @Override
    public Result uploadTopicPhoto(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("请选择要上传的图片");
            }

            // 检查文件大小（10MB = 10 * 1024 * 1024 bytes）
            long maxSize = 10 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return Result.error("图片大小不能超过10MB");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }

            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + suffix;
            
            // 指定存储路径
            String savePath = "D:\\programme\\javaEE\\photo\\TopicPhoto";
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }

            // 创建新文件
            File dest = new File(saveDir, fileName);
            
            // 保存文件
            file.transferTo(dest);

            // 返回文件路径
            String photoUrl = savePath + "\\" + fileName;
            return Result.success(photoUrl);

        } catch (IOException e) {
            return Result.error("图片上传失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)  // 添加只读事务
    public Result getTopicDetail(int topicId) {
        try {
            // 获取话题详情（包含发布者头像）
            TopicDetailVO topicDetail = baseMapper.getTopicDetail(topicId);
            if (topicDetail == null) {
                return Result.error("话题不存在");
            }

            // 获取回复列表（包含回复者头像）
            List<RecoverVO> recoverList = recoverTopicMapper.getRecoverListByTopicId(topicId);
            topicDetail.setRecoverList(recoverList);

            return Result.success(topicDetail);
        } catch (Exception e) {
            return Result.error("获取话题详情失败：" + e.getMessage());
        }
    }
}
